import { _decorator, Animation, Collider2D, Component, Contact2DType, logID, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    //单位血量
    @property
    hp: number = 1
    //敌人飞行速度
    @property
    speed = 300
    //碰撞组件
    @property(Collider2D)
    collider: Collider2D = null
    //动画组件
    @property(Animation)
    anim: Animation = null
    //受伤动画名称
    @property
    animHit: string = ''
    //死亡动画名称
    @property
    animDown: string = ''

    start() {
        //碰撞检测
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onContactPlayer, this);
        }
    }

    update(deltaTime: number) {
        //移动
        if (this.hp > 0) {
            let p = this.node.position
            this.node.setPosition(p.x, p.y - this.speed * deltaTime, p.z)
            //移动出屏幕自毁
            if (p.y < -550) {
                // this.node.destroy()
            }
        }

    }

    hit(n: number, result) {
        //如果生命已经归零跳过方法,并表示此次调用无效
        if (this.hp <= 0) {
            result.flag = false
            result.state = '此目标生命已归零，调用无效'
            return
        }
         //减生命值
        this.hp = this.hp - n
        //如果生命归零玩家坠毁并结束调用,此次调用有效
        if (this.hp <= 0) {
            console.log(`${this.node.name} 生命值归零`);
            this.down()
            result.flag = true
            result.state = '已将此目标生命归零，调用有效'
            return 
        }
        //排除以上情况判断玩家受伤
        console.log(`${this.node.name} 受伤了`);
        //播放受伤动画
        this.anim.play(this.animHit)
        //此次调用有效
            result.flag = true
            result.state = '目标hp已降低，调用有效'
        return
    }

    down(){
        this.anim.play(this.animDown)
        this.anim.once(Animation.EventType.FINISHED, this.node.destroy, this)
    }

    //当接触到玩家扣玩家血量
    onContactPlayer(self, other: Collider2D) {
        console.log('发生一个事件');
        //获取节点名称
        const selfName = self.node.name
        const otherName = other.node.name
        //如果节点名称是Player执行以下操作
        if (otherName === 'Player') {
            console.log(`${selfName} 接触到玩家`);
            //获取玩家相关的自定义脚本组件
            const playerScript = other.node.getComponent('Player')
            //@ts-ignore   //忽略函数未声明错误
            //调用玩家受伤方法
            playerScript.hit(1)
        }

        console.log(`${selfName} 接触到物体 ${otherName}`);
    }
}


